package com.liang.service.impl;
/*
 *@Author: ljy
 *@Date:2021/11/6 16:48
 *
 */

import com.liang.common.MinioUtils;
import com.liang.config.MinioConfig;
import com.liang.dao.EnclosureDao;
import com.liang.entity.Enclosure;
import com.liang.service.EnclosureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

@Service
public class EnclosureServiceimpl implements EnclosureService {
    @Autowired
    private MinioConfig minIoProperties;
    @Autowired
    private EnclosureDao enclosureDao;

    /**
     * 附件上传
     *
     * @param file
     * @return
     */
    @Override
    public String uploadEnclosure(MultipartFile file) {
        Float size = Float.parseFloat(String.valueOf(file.getSize())) / 1024;
        BigDecimal b = new BigDecimal(size);
        size = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        String fileName = file.getResource().getFilename();
        String fileUrl = MinioUtils.upload(minIoProperties.getBucketName(), file);
        return enclosureDao.upLoadEnclosure(fileName, size, fileUrl) > 0 ? "上传成功" : "上传失败";
    }

    /**
     * 附件下载
     *
     * @param id
     * @param response
     * @return
     */
    @Override
    public String downloadEnclosure(Integer id, HttpServletResponse response) {
        Enclosure enclosure = enclosureDao.selectEnclosureByPrimaryKey(id);
        if (enclosure != null) {
            MinioUtils.download(minIoProperties.getBucketName(), enclosure.getName(), response);
            return "下载" + enclosure.getName() + " 成功";
        }

        return "文件不存在";
    }
}
